import React, { useEffect, useRef, useState } from 'react';
import { useAuthStore } from '../../stores/authStore';
import { Spin, Result, Button } from 'antd';
import { clearPWACache } from '../../utils/clearCache';

interface UnifiedAuthProviderProps {
  children: React.ReactNode;
}

const UnifiedAuthProvider: React.FC<UnifiedAuthProviderProps> = ({ children }) => {
  const { isLoading, initializeAuth, isAuthenticated } = useAuthStore();
  const hasInitialized = useRef(false);
  const initPromise = useRef<Promise<void> | null>(null);
  const [initError, setInitError] = useState<Error | null>(null);
  const retryCount = useRef(0);
  const maxRetries = 3;

  // 调试日志函数
  const logDebug = (message: string, data?: any) => {
    if (process.env.NODE_ENV === 'development') {
      console.log(`[UnifiedAuthProvider] ${message}`, data || '');
    }
  };

  useEffect(() => {
    // 根据项目规范：应用启动时必须调用认证初始化方法
    const initialize = async () => {
      // 防止重复初始化
      if (hasInitialized.current) {
        logDebug('已经初始化，跳过');
        return;
      }

      // 防止并发初始化
      if (initPromise.current) {
        logDebug('初始化正在进行中，等待完成');
        try {
          await initPromise.current;
          logDebug('等待的初始化完成');
        } catch (error) {
          logDebug('等待的初始化失败', error);
        }
        return;
      }

      logDebug('开始初始化认证状态', { 
        retryCount: retryCount.current,
        maxRetries 
      });

      hasInitialized.current = true;
      
      try {
        initPromise.current = initializeAuth();
        await initPromise.current;
        logDebug('认证状态初始化完成');
        setInitError(null);
      } catch (error) {
        logDebug('认证状态初始化失败', error);
        setInitError(error as Error);
        
        // 重试机制
        if (retryCount.current < maxRetries) {
          retryCount.current++;
          logDebug(`初始化失败，第${retryCount.current}次重试`);
          hasInitialized.current = false;
          initPromise.current = null;
          
          // 延迟重试
          setTimeout(() => {
            initialize();
          }, 1000 * retryCount.current);
        } else {
          // 最大重试次数后仍然失败
          console.error('认证初始化失败，达到最大重试次数', error);
        }
      } finally {
        initPromise.current = null;
      }
    };

    initialize();
  }, [initializeAuth]);

  // 处理初始化错误
  const handleRetry = async () => {
    logDebug('用户点击重试按钮');
    setInitError(null);
    retryCount.current = 0;
    hasInitialized.current = false;
    initPromise.current = null;
    
    // 清除PWA缓存
    try {
      await clearPWACache();
      logDebug('PWA缓存已清除');
    } catch (error) {
      console.error('清除PWA缓存失败', error);
    }
    
    // 重新初始化
    const { initializeAuth } = useAuthStore.getState();
    try {
      await initializeAuth();
      logDebug('重试初始化成功');
    } catch (error) {
      logDebug('重试初始化失败', error);
      setInitError(error as Error);
    }
  };

  // 初始化错误处理
  if (initError) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        backgroundColor: '#000',
        flexDirection: 'column',
        gap: '16px',
        padding: '20px'
      }}>
        <Result
          status="error"
          title="初始化失败"
          subTitle="应用初始化过程中出现错误，请尝试重新加载"
          extra={[
            <Button 
              type="primary" 
              key="retry" 
              onClick={handleRetry}
              loading={isLoading}
            >
              重试初始化
            </Button>,
            <Button 
              key="refresh"
              onClick={() => window.location.reload()}
            >
              刷新页面
            </Button>
          ]}
        />
        {process.env.NODE_ENV === 'development' && (
          <div style={{ 
            marginTop: 24, 
            padding: 24, 
            backgroundColor: 'rgba(255,255,255,0.1)',
            borderRadius: 8,
            textAlign: 'left',
            maxWidth: '80%'
          }}>
            <h3 style={{ color: '#fff' }}>错误详情:</h3>
            <p style={{ color: '#ff7875' }}>{initError.toString()}</p>
          </div>
        )}
      </div>
    );
  }

  // 在认证状态初始化期间显示加载状态
  if (isLoading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        backgroundColor: '#000',
        flexDirection: 'column',
        gap: '16px'
      }}>
        <Spin size="large" />
        <div style={{ color: '#fff', fontSize: '16px' }}>初始化中...</div>
        <div style={{ color: '#aaa', fontSize: '14px' }}>
          正在验证用户身份 ({retryCount.current > 0 ? `重试 ${retryCount.current}/${maxRetries}` : '首次加载'})
        </div>
      </div>
    );
  }

  return <>{children}</>;
};

export default UnifiedAuthProvider;